import { getInfo, managerLogin, teacherLogin } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    account: '',
    roles: [],
    org_id: '',
    org_name: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ACCOUNT: (state, account) => {
    state.account = account
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ORG_ID: (state, org_id) => {
    state.org_id = org_id
  },
  SET_ORG_NAME: (state, org_name) => {
    state.org_name = org_name
  },
}

const actions = {
  login({ commit }, userInfo) {
    const { username, password, type } = userInfo
    return new Promise((resolve, reject) => {
      if(type == 'manager') {
        managerLogin({ account: username.trim(), password: password}).then(response => {
          const { data } = response
          commit('SET_TOKEN', data.Token)
          setToken(data.Token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      }else if(type === 'teacher') {
        teacherLogin({ tno: username.trim(), password: password}).then(response => {
          const { data } = response
          commit('SET_TOKEN', data.Token)
          setToken(data.Token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      }
    })
  },

  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response
        if (!data) {
          return reject('验证失败，请重新登录')
        }
        if (data.Role === 'manager') {
          commit('SET_ROLES', [ data.Role ])
          commit('SET_ACCOUNT', data.Account)
          commit('SET_NAME', data.Name)
        } else if (data.Role === 'teacher') {
          commit('SET_ROLES', [ data.Role ])
          commit('SET_ACCOUNT', data.Tno)
          commit('SET_NAME', data.Name)
          commit('SET_ORG_ID', data.Org_id)
          commit('SET_ORG_NAME', data.Org_name.String)
        } else {
          reject('获取角色失败')
        }

        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  logout({ commit }) {
    removeToken()
    resetRouter()
    commit('RESET_STATE')
  },

  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
